<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/30
 * Time: 10:26
 */

namespace app\Flagship\Controller;


use app\Model\AdminModel;
use app\Model\AdminRoleModel;
use app\Model\CommentModel;
use app\Model\FlagshipModel;
use app\Model\FlagshipSetModel;
use app\Model\GoodsModel;
use app\Model\MenuModel;
use app\Model\OrderActionModel;
use app\Model\OrderGoodsModel;
use app\Model\OrderModel;
use app\Model\RegionModel;
use app\Model\ReturnGoods;
use app\Model\ShippingAreaModel;
use app\Model\SpecGoodsPriceModel;
use app\Model\SystemMenuModel;
use app\Model\UserLeverModel;
use app\Model\UsersModel;
use think\Collection;
use think\Controller;
use think\Request;

class Common extends Controller
{

    /*
     * tp5构造函数  判断是否登陆
     */
    public function _initialize()
    {
        if (!session('?Flagship')){
            $this->redirect('Login/login');
        }
        //删除过期订单（超过一天未支付）
        $where=['add_time'=>['<',time()-86400],
                'pay_status'=>0,//未支付
        ];
        $getPast=OrderModel::where($where)->column('order_id');
        if ($getPast){
            OrderModel::destroy($getPast);
        }
        $getWithdrawals= OrderModel::where('order_status',0)//订单信息
            ->order('add_time','desc')->select();
//        dump($getWithdrawals);die();
        $this->assign('orderindex',$getWithdrawals);

        $getReturnGoods = ReturnGoods::where('status','<>',2)->select();//退换货申请
        $this->assign('return_goods',$getReturnGoods);

        $getcomment=CommentModel::where('reply',0)->where('parent_id',0)->select();//评论信息
        $this->assign('commentreply',$getcomment);
    }


    /*
     * 获取控制器和方法名缓存进menus
     * $menus 对比tp_menu表的menus
     */
    public function getConAndAct($menus='')
    {
        $menu['controller'] = Request::instance()->controller(); // 控制器名
        $menu['action'] = Request::instance()->action();     // 方法名
        $menu['menus']=$menus;
        session('menus',$menu);
    }
    /*
     * 根据地址反馈经纬度等信息
     */
    public function location2()
    {
        $getData=input();
        $getData['address']='北京市市辖区北京市详细地址';
        $url="https://apis.map.qq.com/jsapi?qt=poi&wd=".$getData['address'];
//       return retJson(null,0,$getData['address']);die();
        $data = location($url);
        return $data['detail']['pois'];
    }



    /*
     * 修改信息页面
     */
    public function setpassv()
    {
        $getRegion=RegionModel::where('level','=',1)->column('name','id');
        $data['province']=$getRegion;//省数据传入view

            $getAdmin = FlagshipModel::find(session('Flagship.id'));//获取信息
            $data['data']=$getAdmin;

//            dump($getAdmin->toArray());die();

        return view('Login/setpassv',$data);
    }

    /*
     * 修改密码
     */
    public function setPass()
    {
        $getData=input('post.');
        //原密码是否正确
       if (session('Flagship.password')==encryption($getData['password'])) {
           $updata=[
               'admin_id'=>session('Flagship.id'),
               'password'=>encryption($getData['newpassword2']),
           ];
            $setAdmin=FlagshipModel::update($updata);

           $this->upSess();
           return setDatabase($setAdmin,'改密');
       }
        setDatabaseDef(false,'原密码错误');

    }
    /*
     * 修改信息（地址、经纬度、邮箱等）
     */
    public function set_jwd()
    {
        $getData=input('post.');
        if(isset($getData['balance'])){
            setDatabaseDef(false,'非法操作');
        }
        $setAdmin=FlagshipModel::update($getData);
        $getData['id']=session('Flagship.id');
        $this->upSess();
        return setDatabase($setAdmin);

    }
    /*
     * 更新session---管理员
     */
    public function upSess()
    {
        $getFlag=FlagshipModel::find(session('Flagship.id'));//旗舰账号信息
        $getSetFlag=FlagshipSetModel::select();
        $getFlag['discount']=$getSetFlag[0]->val;//公共设置信息--折扣
        $getFlag['one_limit']=$getSetFlag[1]->val;//公共设置信息---第一单需要到达的额度
        session('Flagship',$getFlag);
    }
    /**
     * @param string $method  方法名
     * @param string $page    页面
     * 数据验证
     */
    function veri($method='',$page=''){
        $validate = validate($method);
        $validate->scene($page);
        if(!$validate->check(input('post.'))){
            $this->error($validate->getError());
        }
    }

    /*
     * 根据订单id返回订单内商品信息
     * $orderId 订单id
     */
    public function goods($orderId='')
    {
       $getGoods= OrderGoodsModel::where('order_id','=',$orderId)->select();
       return $getGoods;
    }
    /*
     * 订单操作
     *  $order 该订单（obj）
     *  $update=[//字段               值
                $status_code=>$status_val
        ];
     * $status_val 要改变的状态值（0,1,2）
     * $action 操作描述
     * $note 操作备注
     */
    public function setOrderC($order_id,$update,$action='',$note='')
    {

        if (isset($update['shipping_status'])&&$update['shipping_status']==2){//如果完成收货
            $update['order_status']=2; //订单完成
        }
        $setOrder = OrderModel::where('order_id',$order_id)->update($update);
//        return setDatabase($setOrder);
        setDatabaseDef($setOrder,$action.'失败');
        $this->orderActionLog($order_id,$action,$note);//添加订单操作记录
    }

    /*
     * 订单操作记录
     * $order_id 该订单id
     * $action 操作描述
     * $note 操作备注
     */
    public function orderActionLog($order_id,$action='',$note='')
    {


        $order = OrderModel::find($order_id);
        $data['order_id'] = $order->order_id;

        $data['action_type'] = 2;//操作人类型--0管理员 1加盟商 2客户
        $data['action_user'] = session('Flagship.id');//操作人id
        $data['action_note'] = $note;
        $data['order_status'] = $order['order_status'];
        $data['pay_status'] = $order['pay_status'];
        $data['shipping_status'] = $order['shipping_status'];
        $data['log_time'] = time();
        $data['status_desc'] = $action;

        $orderActionLog = OrderActionModel::insert($data);
        setDatabaseDef($orderActionLog,$action.'失败');
    }


    /*
     * 商品列表（包含不同规格）
     */
    public function goodsEndSpec()
    {
        //商品列表
        $goods = GoodsModel::column('*','goods_id');
        //规格表
        $data['spec']=SpecGoodsPriceModel::select();

        foreach ($data['spec'] as $k => $v) {
            if (empty($goods[$v->goods_id]['spec'])){
                $goods[$v->goods_id]['spec']=[];
            }
            array_push($goods[$v->goods_id]['spec'],$v->toArray());
        }
        return  $goods;
    }
   /*
    * 订单所包含的商品信息详情
    * $order_data 订单包含的商品数组[goods_id=>商品id，key=>商品规格，num=>数量]
    */
    public function order_goods_data($order_data=[])
    {
        foreach ($order_data as $k=>$v){
            $where=['goods_id'=>$order_data['goods_id']];
            //商品图片路径
            $moneyq= GoodsModel::where($where)->find();//默认商品信息()
            $data[$k]['original_img']=$moneyq->original_img;
            //判断该商品是否有规格
            if ($order_data['spec_key']==''){//没有规格
                $data[$k]['market_price']=$moneyq->market_price;//市场价
                $data[$k]['shop_price']=$moneyq->shop_price;//本店价
            }else{//有规格
                $moneyq=SpecGoodsPriceModel::where($where)->where('key',$v->spec_key)->find();//有规格替换规格信息
                $data[$k]['market_price']=$moneyq->price_tall;//市场价
                $data[$k]['shop_price']=$moneyq->price;//本店价
            }
            $data[$k]['store_count']=$moneyq->store_count;//库存
        }
        return $data;
    }

    /*
    * 减少相应库存（含规格）
    * $orderGoodsId 订单链接商品表id
    */
    public function setStoreCount($orderGoodsId)
    {
        $getOrderGoods=OrderGoodsModel::where('order_id','=',$orderGoodsId)->select();
        foreach ($getOrderGoods as $k=>$v){
            if ($v->spec_key==''){//没有规格
                GoodsModel::where('goods_id','=',$v->goods_id)->setDec('store_count',$v->goods_num);

            }else{//有规格
                SpecGoodsPriceModel::where('goods_id','=',$v->goods_id)
                    ->where('key','=',$v->spec_key)->setDec('store_count',$v->goods_num);
            }
        }
    }
    /*
    * 省内是否还有其他分店
    * $province_name 省份名称
    */
    public function province_flag($province_name)
    {
        $getFlag=FlagshipModel::where('provinceName',$province_name)->find();
        if ($getFlag){
            return -1;
        }
        return 0;
    }

    /**
     * 记录帐户变动
     * @param   float   $user_money     可用余额变动
     * @param   string  $desc    变动说明
     * @param   float   distribut_money 分佣金额
     * @return  bool
     */
    function accountLog($user_money=0, $desc='',$order_id='',$order_sn=''){
        /* 插入帐户变动记录 */
        $account_log = array(
            'user_id'       => session('Flagship.id'),//加盟商id
            'user_money'    => $user_money,//金额（正数充值，负数消费）
            'user_type'    => 1,
            'change_time'   => time(),
            'desc'   => $desc,
            'order_id'=>$order_id,
            'order_sn'=>$order_sn,
        );
        Db('tp_account_log')->insert($account_log);
        return true;

    }
}